﻿using AutoMapper;
using MediatR;
using SqlSugar;
using WarehouseManagement.Application.Command.ShipApplyCommand;
using WarehouseManagement.Domain.DTO.ShipApply;
using WarehouseManagement.Domain.Entity;
using WarehouseManagement.Infrstructre.Interface;

namespace WarehouseManagement.Application.CommandHandler.ShipApplyCommandHandlers
{
    /// <summary>
    /// 确认发货添加
    /// </summary>
    public class ADDDeliveryConfirmationCommandHandler : IRequestHandler<ADDDeliveryConfirmationCommand, int>
    {
        private readonly lnterfaceDeliveryConfirmationRepository _deliveryConfirmationRepository;
        private readonly ISqlSugarClient db;
        private readonly IShipRequestRepository _ship;
        private readonly IShipRequestProRepository _shipPro;
        private readonly IMapper mapper;

        public ADDDeliveryConfirmationCommandHandler(lnterfaceDeliveryConfirmationRepository deliveryConfirmationRepository, ISqlSugarClient db, IShipRequestRepository ship, IShipRequestProRepository shipPro, IMapper mapper)
        {
            _deliveryConfirmationRepository = deliveryConfirmationRepository;
            this.db = db;
            _ship = ship;
            _shipPro = shipPro;
            this.mapper = mapper;
        }

        public async Task<int> Handle(ADDDeliveryConfirmationCommand request, CancellationToken cancellationToken)
        {
            //开启事物
            db.Ado.BeginTran();
            try
            {
                request.add.DeliveryConfirmationNumber = Guid.NewGuid().ToString().Replace("-", "");
                await _deliveryConfirmationRepository.AddAsync(request.add);


                var newlist = (await _ship.GetAll()).First(x => x.ShippRequestAppId == request.add.ShippRequestAppId);
                newlist.ShipState = 2;
                await _ship.UpdateAsync(newlist);
                //提交事物  
                db.Ado.CommitTran();

                return 1;





            }
            catch (Exception)
            {
                //回滚事物
                db.Ado.RollbackTran();
                throw;
            }
        }
    }
}
